(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.patchTemplate.createController', createController);
	createController.$inject = [ '$scope', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService', 'storageService', 
			'patchTemplateService' ];
	function createController($scope, Constants, modalService, gridService, layoutConfig, validatorConfig, authService, storageService, patchTemplateService) {
		var ctrl = this, params = $scope.$stateParams.params, errorMessage = {};
		var log = $scope.loggerFactory.getLogger("patchTemplateCreate");
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.patchTemplate = {};
		ctrl.patchTemplate.useGlobalDb = ctrl.patchTemplate.useGlobalDb;
		ctrl.patchTemplate.dPatchTplParms = ctrl.patchTemplate.dPatchTplParms || [];
		ctrl.parms = [];
		
		ctrl.init = function() {
			if(ctrl.validatorConfig) ctrl.layoutConfig.formConfigs.dPatchTplParms.tableConfigs.table.validatorConfig = ctrl.validatorConfig.dPatchTplParms;
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.dPatchTplParms.tableConfigs.table, rowSelectionChanged);
			ctrl.innerGridOptions.data = 'vm.patchTemplate.dPatchTplParms';
			ctrl.innerGridOptions.enableOperation = true;
			ctrl.innerGridOptions.addRow = function(row){
			};
			
			authService.create($scope.$stateParams.params).then(function(response) {
				patchTemplateService.initOptions(ctrl).then(function(result){
					ctrl.patchTemplate = response.data || params;
					ctrl.patchTemplate.dPatchTplParms = ctrl.patchTemplate.dPatchTplParms || [];
				});
			});
			ctrl.dPatchTplParmOptions = parmTypeOptions().data;
		};
		
		function parmTypeOptions() {
			return {
				"data" : [ {
					"label" : "Date",
					"value" : "java.sql.Date"
				},{
					"value" : "java.lang.Double",
					"label" : "Double"
				}, {
					"value" : "java.lang.Float",
					"label" : "Float"
				} , {
					"value" : "java.lang.Integer",
					"label" : "Integer"
				} , {
					"value" : "java.lang.Long",
					"label" : "Long"
				} , {
					"value" : "java.lang.Short",
					"label" : "Short"
				} , {
					"value" : "java.lang.String",
					"label" : "String"
				} , {
					"value" : "java.sql.Timestamp",
					"label" : "Timestamp"
				}]
			};
		}
		
		//select ${},
		ctrl.filter = function (string) {
			var subParm;
			if (string != null){
				var m = string.indexOf('{');
				var n = string.indexOf('}');
				if ( m != -1){
					subParm = string.substring(m+1, n);
					ctrl.parms.push(subParm);
					if (string.length >= n){						
						string = string.substring(n +1, string.length);
						ctrl.filter(string);
					}
				}
			}
			return ctrl.filterRecopy(ctrl.parms);
		};
		
		//filter recopy
		ctrl.filterRecopy = function (parms){
			ctrl.parmsCopy = [];
			for (var i=0; i< parms.length; i++){
				if (ctrl.parmsCopy.indexOf(parms[i]) == -1){
					ctrl.parmsCopy.push(parms[i]);
				};
			};
			return ctrl.parmsCopy;
		};
		
		//set useGlobalValue according sqlScript's tableName contains 'G' orNot 
		ctrl.setUseGlobalValue = function(){
			ctrl.patchTemplate.sqlScript = ctrl.patchTemplate.sqlScript;
			if (ctrl.patchTemplate.sqlScript != null){
				var parm = ctrl.patchTemplate.sqlScript.toString();
				if (parm.indexOf('_G_')!= -1){
					ctrl.patchTemplate.useGlobalDb = 'Y';
				} else {
					ctrl.patchTemplate.useGlobalDb = 'N';
				}
			}
		};
		
		ctrl.createSave = function() {
			var i = 0;
			//clear
			ctrl.parms = [];
			ctrl.parmsCopy = [];
			ctrl.patchTemplate.sqlScript = ctrl.patchTemplate.sqlScript;
			if (ctrl.patchTemplate.sqlScript != null){
				var parm = ctrl.patchTemplate.sqlScript.toString();
				var parms = ctrl.filter(parm);
				ctrl.patchTemplate.dPatchTplParms = ctrl.patchTemplate.dPatchTplParms || [];
				if (ctrl.patchTemplate.dPatchTplParms && ctrl.patchTemplate.dPatchTplParms.length === parms.length){	
					angular.forEach( parms, function (pValue){				
						angular.forEach(ctrl.patchTemplate.dPatchTplParms, function (value, key){
							if (value ){
								if ( value.parmName === pValue){							
									i ++;
									value.parmName = pValue;
									value.dpatchParmId = value.dpatchParmId;
									value.parmType = value.parmType;
									value.parmMaxLen = value.parmMaxLen;
									value.parmDesc = value.parmDesc;
								}
							} else {
								modalService.openErrorDialogs({
									'messages' : [ "js.pub.error.params-unused"+ value.parmName]
								});
							}
						});
					});
					if ( i === parms.length ){
						if (ctrl.patchTemplate.taskId) {
							return authService.createContinueSave(ctrl.patchTemplate).then(saveSuccessful, saveFailed);
						} else {
							return authService.createSave(ctrl.patchTemplate).then(saveSuccessful, saveFailed);
						}
					} else {
						modalService.openErrorDialogs({
							'messages' : ["js.pub.error.params-undefined"]
						});
					}
				} else {
					modalService.openErrorDialogs({
						'messages' : [ "js.pub.error.params-doesnot equals to sql script in need" + parms ]
					});
				}
			} else {
				if (ctrl.patchTemplate.taskId) {
					return authService.createContinueSave(ctrl.patchTemplate).then(saveSuccessful, saveFailed);
				} else {
					return authService.createSave(ctrl.patchTemplate).then(saveSuccessful, saveFailed);
				}
			}
		};

		ctrl.createSubmit = function() {
			var i = 0;
			ctrl.parms = [];
			ctrl.parmsCopy = [];
			ctrl.patchTemplate.sqlScript = ctrl.patchTemplate.sqlScript;
			if (ctrl.patchTemplate.sqlScript != null){				
				var parm = ctrl.patchTemplate.sqlScript.toString();
				var parms = ctrl.filter(parm);
				ctrl.patchTemplate.dPatchTplParms = ctrl.patchTemplate.dPatchTplParms || [];
				if (ctrl.patchTemplate.dPatchTplParms  && ctrl.patchTemplate.dPatchTplParms.length === parms.length){
					angular.forEach( parms, function (pValue){				
						angular.forEach(ctrl.patchTemplate.dPatchTplParms, function (value, key){
							if (value ){
								if ( value.parmName === pValue){							
									i ++;
								}
							} else {
								modalService.openErrorDialogs({
									'messages' : [ "js.pub.error.params-unused"+ value.parmName]
								});
							}
						});
					});
					if ( i === parms.length ){
						if (ctrl.patchTemplate.taskId) {
							return authService.createContinueSubmit(ctrl.patchTemplate).then(submitSuccessful, submitFailed);
						} else {
							return authService.createSubmit(ctrl.patchTemplate).then(submitSuccessful, submitFailed);
						}
					} else {
						modalService.openErrorDialogs({
							'messages' : [ 'js.pub.error.params-undefined']
						});
					}
				} else {
					modalService.openErrorDialogs({
						'messages' : [ 'js.pub.error.params-doesnot equals to sql script in need' + parms ]
					});
				}
			} else {
				if (ctrl.patchTemplate.taskId) {
					return authService.createContinueSubmit(ctrl.patchTemplate).then(submitSuccessful, submitFailed);
				} else {
					return authService.createSubmit(ctrl.patchTemplate).then(submitSuccessful, submitFailed);
				}
			}
		};
			
		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedDPTplParmList = selectedRows;
		}

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.patchTemplate.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.patchtemplate.list',
					'state' : 'cda.patchTemplate.list',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data && response.data.model) {
				ctrl.patchTemplate = response.data.model;
			}
			if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);